package com.cll.learn.monitor.thread;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 描述信息:
 *
 * @author CLL
 * @version 1.0
 * @date 2020/9/29 14:35
 */
public class CheckPoolTask implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(CheckPoolTask.class);

    private static final Map<String, CustomThreadPoolExecutor> THREAD_POOL_EXECUTOR_MAP = new ConcurrentHashMap<>();

    public static void addThreadPool(CustomThreadPoolExecutor threadPoolExecutor){
        if (!THREAD_POOL_EXECUTOR_MAP.containsKey(threadPoolExecutor.getName())) {
            THREAD_POOL_EXECUTOR_MAP.put(threadPoolExecutor.getName(), threadPoolExecutor);
        }
    }

    private static void removeThreadPool(String threadPoolName){
        THREAD_POOL_EXECUTOR_MAP.remove(threadPoolName);
    }

    @Override
    public void run() {
        if (logger.isDebugEnabled()) {
            logger.debug(">>>>>> check thread pool used is starting...");
        }
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, CustomThreadPoolExecutor> entry : THREAD_POOL_EXECUTOR_MAP.entrySet()) {
            if (entry.getValue().isShutdown() || entry.getValue().isTerminated() || entry.getValue().isTerminating()) {
                CheckPoolTask.removeThreadPool(entry.getKey());
            } else {
                sb.append("\npoolName=[").append(entry.getKey())
                        .append("] core thread number=[").append(entry.getValue().getCorePoolSize())
                        .append("] active number=[").append(entry.getValue().getActiveCount())
                        .append("] max pool size=[").append(entry.getValue().getMaximumPoolSize())
                        .append("] queue wait size=[").append(entry.getValue().getQueue().size())
                        .append("] had execute thread number=[").append(entry.getValue().getCompletedTaskCount()).append("]");
                if (entry.getValue().getMaximumPoolSize() == entry.getValue().getActiveCount()) {
                    sb.append("\n======================================this thread pool is full fire====================================================");
                }
            }
        }
        logger.info("===>>> thread pool used info: {}", sb.toString());
    }
}
